import Vue from 'vue'
import VueRouter from 'vue-router'
//引入Login组件
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import StudentList from '../components/student/StudentList.vue'
import OneStudent from '../components/student/OneStudent.vue'
import AddStudent from '../components/student/AddStudent.vue'
import UpdateStudent from '../components/student/UpdateStudent.vue'
import DeleteStudent from '../components/student/DeleteStudent.vue'
import CountByAge from '../components/student/CountByAge.vue'
import CountByAddress from '../components/student/CountByAddress.vue'
import CountByPolitics from '../components/student/CountByPolitics.vue'

Vue.use(VueRouter)

  const routes =[
    {
      path:"/",
      //重定向
      redirect:"/login"
    },
    {
      path:"/login",
      component:Login
    },
    {
      path:"/home",
      component:Home,
      redirect:"/welcome",
      children:[
        {path:"/welcome",component: Welcome,},
        {path:"/findAll",component: StudentList,},
        {path:"/findOne",component: OneStudent,},
        {path:"/add",component: AddStudent,},
        {path:"/update",component: UpdateStudent,},
        {path:"/delete",component: DeleteStudent,},
        {path:"/ageCount",component: CountByAge,},
        {path:"/addressCount",component: CountByAddress,},
        {path:"/politics",component: CountByPolitics,},
      ]
    }
  ]
const router = new VueRouter({
  routes
})

/*const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject){
    if(onResolve || onReject) return originalPush.call(this, location,onResolve,onReject)
    return originalPush.call(this, location).catch(error => error)
}*/

//挂载路由导航守卫
router.beforeEach((to, from, next)=>{
  //to将要访问
  //from从哪访问
  //next是否通行
  if(to.path == '/login') return next(); //访问首页，通行
  //获取user
  const userFlag = window.sessionStorage.getItem("user"); //取出当前用户
  if(!userFlag) return next('/login'); //无值返回登录页
  next(); //符合要求 通行
})
export default router

